<?php
/**
 * Created by PhpStorm.
 * User: xing
 * Date: 2018/11/15
 * Time: 7:12 PM
 */
namespace app\wechat\controller;

use think\Config;
use think\Db;
use think\Validate;
use app\enumerations\MessageIsDelEnum;

class Message extends Common {

    /**
     * 我的留言列表
     * @return \think\response\Json
     */
    public function myMessageList() {

        $currentCustomer = $this->request->currentCustomer;

        $messageList = $this->messageService
            ->getMessageListByCustomerId($currentCustomer['id']);

        $firstMessage["message_id"] = 0;
        $firstMessage["owner"] = 1;
        $firstMessage["message"] = isNullOrEmpty($currentCustomer['sign'])
            ? config('constants.defaultSign') : $currentCustomer['sign'];
        $firstMessage["time"] = isNullOrEmpty($currentCustomer["update_sign_time"])
            ? $currentCustomer["create_time"] : $currentCustomer["update_sign_time"];
        $firstMessage["nickname"] = $currentCustomer['nickname'];
        $firstMessage["headimgurl"] = $currentCustomer['headimgurl'];

        $list = [];

        array_push($list, $firstMessage);
        $list = array_merge($list, object2array($messageList));

        $returnData['list'] = $list;
        $returnData['total_counts'] = count($list);

        return successReturn($returnData);

    }

    /**
     * 别人店的留言列表
     * @return \think\response\Json
     */
    public function otherMessageList() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn("errorWechat.errorCustomerNotFound");
        }

        $messageList = $this->messageService
            ->getMessageListByCustomerId($customer['id']);

        foreach ($messageList as $key=>$val) {

            $val['my_message'] = 0;
            if ($val['customer_id'] == $currentCustomer['id']) {
                $val['my_message'] = 1;
            }
        }

        $firstMessage["message_id"] = 0;
        $firstMessage["owner"] = 1;
        $firstMessage["message"] = isNullOrEmpty($customer['sign'])
            ? config('constants.defaultSign') : $customer['sign'];
        $firstMessage["time"] = isNullOrEmpty($customer["update_sign_time"])
            ? $customer["create_time"] : $customer["update_sign_time"];
        $firstMessage["nickname"] = $customer['nickname'];
        $firstMessage["headimgurl"] = $customer['headimgurl'];
        $firstMessage['my_message'] = 0;

        $list = [];

        array_push($list, $firstMessage);
        $list = array_merge($list, object2array($messageList));

        $returnData['list'] = $list;
        $returnData['total_counts'] = count($list);

        return successReturn($returnData);

    }

    /**
     * 店主删除留言
     * @return \think\response\Json
     */
    public function deleteMessage() {

        $currentCustomer = $this->request->currentCustomer;
        $messageId = $this->request->post("messageId");

        $message = $this->messageService->findById($messageId);

        if (isNullOrEmpty($message)) {
            return errorReturn("errorWechat.errorMessageNotFound");
        }

        if ($message['is_del'] != MessageIsDelEnum::getEnumValue(MessageIsDelEnum::VALID_CODE)) {
            return errorReturn("errorWechat.errorMessageNotFound");
        }

        // 判断留言是否归我所属
        if ($message['mch_customer_id'] != $currentCustomer['id']) {
            return errorReturn("errorWechat.errorMessageDeleteNoAuth");
        }

        Db::startTrans();
        try {

            // 删除留言
            $messageData['is_del'] = MessageIsDelEnum::getEnumValue(MessageIsDelEnum::DELETE_CODE);

            $this->messageService->updateByIdAndData($messageId, $messageData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn("errorWechat.errorService");

        }

        return successReturn();

    }

    /**
     * 提交留言
     * @return \think\response\Json
     */
    public function submitWriteMessage() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");
        $message = $this->request->post("message");

        $rule = [
            'message'  => 'require|max:30',
        ];
        $msg = [
            'message.max' => '留言长度不可大于30',
        ];
        $data = [
            'message'  => $message,
        ];
        $validate = Validate::make($rule, $msg);
        if(!$validate->check($data)) {
            return errorReturn("errorWechat.errorDataFormat", $validate->getError());;
        }

        // 不能给自己留言
        if ($currentCustomer['id'] == $customerId) {
            return errorReturn("errorWechat.errorWriteMessageForOwn");
        }

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn("errorWechat.errorCustomerNotFound");
        }

        Db::startTrans();
        try {

            // 添加留言
            $messageData['mch_customer_id'] = $customerId;
            $messageData['consume_customer_id'] = $currentCustomer['id'];
            $messageData['message'] = $message;

            $saveMessageRes = $this->messageService->saveByData($messageData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn("errorWechat.errorService");

        }

        $returnData['message_id'] = $saveMessageRes['id'];
        $returnData['owner'] = 0;
        $returnData['message'] = $message;
        $returnData['time'] = getCurrentTime();
        $returnData['nickname'] = $currentCustomer['nickname'];
        $returnData['headimgurl'] = $currentCustomer['headimgurl'];
        $returnData['my_message'] = 1;

        return successReturn($returnData);

    }

    /**
     * 删除我的留言
     * @return \think\response\Json
     */
    public function deleteMyMessage() {

        $currentCustomer = $this->request->currentCustomer;
        $messageId = $this->request->post("messageId");

        $message = $this->messageService->findById($messageId);

        if (isNullOrEmpty($message)) {
            return errorReturn("errorWechat.errorMessageNotFound");
        }

        if ($message['is_del'] != MessageIsDelEnum::getEnumValue(MessageIsDelEnum::VALID_CODE)) {
            return errorReturn("errorWechat.errorMessageNotFound");
        }

        // 判断留言是否归我所属
        if ($message['consume_customer_id'] != $currentCustomer['id']) {
            return errorReturn("errorWechat.errorMessageDeleteNoAuth");
        }

        Db::startTrans();
        try {

            // 删除留言
            $messageData['is_del'] = MessageIsDelEnum::getEnumValue(MessageIsDelEnum::DELETE_CODE);

            $this->messageService->updateByIdAndData($messageId, $messageData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn("errorWechat.errorService");

        }

        return successReturn();

    }

}